#include <stdio.h>
#include <math.h>

#define FOSC 40000000
#define TIMERPERIOD (double)(4*(1000000000.0 / FOSC))

double next_step_period(double current_period, double current_sum, double time_accel) {
  double currentns, sumns, accelns, newns;
  currentns = current_period * TIMERPERIOD;
  sumns = current_sum * TIMERPERIOD;
  accelns = time_accel * 1000000000;
  
  newns = currentns - exp(sumns - accelns) * currentns;

  return (newns / TIMERPERIOD);
  
}

int main(void) {
  unsigned int i;
  unsigned int v, vfinal, vinitial;
  int a, j, l;
  unsigned int nbinc, nbacc, step360;
  double t=0.0, dt=0.0, vang;
  unsigned int timer, timerinitial, timerfinal, timerstep, timerperiod, totaltime;
  unsigned int nbpas=0, totalpas;

  totaltime=2000000000;
  totalpas=0;
  i=0;
  nbinc = 50;
  nbacc = 200;
  step360 =400;
  timerperiod=(totaltime/nbacc) / TIMERPERIOD;

  timerstep = 65535;
  timerfinal=6250;
  vfinal=(((360 * 1000000) / step360) * 1000) / (timerfinal * TIMERPERIOD); 
  vinitial=(((360 * 1000000) / step360) * 1000) / (timerinitial * TIMERPERIOD); 
//vfinal=1440.0;

  if (totalpas == 0) {
    nbinc = 50;
    nbacc = 200;
  } else {
    unsigned int timermean;
    timermean= ((360.0 / step360) / ((vfinal-vinitial)/2)) * (1000000000.0 / TIMERPERIOD);
    totaltime = timermean *totalpas *TIMERPERIOD;
    nbacc=totalpas/6;
    nbinc=(nbacc/4);
  }

  timer=timerstep;
  vang=(360.0 / step360) / ( (double)timer * TIMERPERIOD / 1000000000.0); 
  v=(((360 * 1000000) / step360) *1000) / (timer * TIMERPERIOD); 
  a=0; j=(vfinal - v) / ((nbacc - nbinc + 1) * nbinc); if (j==0) j=1;
  l = 
  printf("vfinal = %d vinitial = %d j = %d timerperiod = %d\n", vfinal, vinitial, j, timerperiod);
  while (timer > timerfinal  + 1) {
    timerstep+=timer;
    nbpas+=1;
    if (timerstep >= timerperiod) {
      if (i < nbinc) a += j;
      if (i > (nbacc - nbinc)) a -= j;
      v = v + a;
      timer = (((360 * 1000000) / step360) * 1000) / (v * TIMERPERIOD);
      timerstep=timer;
      printf("time %g -- step %d: acc. step %d, timer %d  v %d a %d\n", t, nbpas, i, timer,  v, a);
      i+=1;
    }
    t = t + ((double)timer * TIMERPERIOD / 1000000000.0);
    vang=(360.0 / step360) / ( (double)timer * TIMERPERIOD / 1000000000.0); 
    /*    printf("%g %g %g %d\n", t,  timer, vang, i);*/
    //printf("%g %g %g %g %d\n", t, timer, vang, v, i);
    //printf("%g %g\n", t, vang);
  }

  exit(0);
}
